package antidestiny.java2dex.ui.dialog;

import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.EditText;

import java.io.File;
import java.io.IOException;

import antidestiny.java2dex.Jing;
import antidestiny.java2dex.R;
import antidestiny.java2dex.file.FileConstructor;
import antidestiny.java2dex.utils.StringCheck;

/**
 * Created by Hero on 2016/12/30.
 */

public class NewFileDialogBuilder {

    FileBuilderI builderInterface;

    public NewFileDialogBuilder() {
    }

    public void setBuilderInterface(FileBuilderI builderInterface) {
        this.builderInterface = builderInterface;
    }

    /**
     * 显示创建工程的对话框
     */
    public AlertDialog newProject(final Context context, final File dir) {
        final FileConstructor fileConstructor = new FileConstructor();
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
        final View root = View.inflate(context, R.layout.dialog_new_project, null);
        dialogBuilder.setView(root)
                .setNegativeButton(android.R.string.cancel, null)
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String projectName = ((EditText) root.findViewById(R.id.edit_name)).getText().toString();
                        String packageStr = ((EditText) root.findViewById(R.id.edit_package)).getText().toString();
                        String errMsg = "";
                        FileConstructor.TaskInfo taskInfo = null;

                        //检查输入
                        String check=StringCheck.checkPackage(packageStr);
                        if (check!=null){
                            errMsg+=check+'\n';
                            errorDialog(context,R.string.title_wrong_input,errMsg).show();
                            return;
                        }
                        check=StringCheck.checkProjectName(projectName);
                        if (check!=null){
                            errMsg+=check+'\n';
                            errorDialog(context,R.string.title_wrong_input,errMsg).show();
                            return;
                        }

                        //尝试建造文件
                        try {
                            taskInfo = fileConstructor.createProject(projectName, packageStr, dir);
                        } catch (IOException e) {
                            e.printStackTrace();
                            errMsg += e;
                        }
                        if (taskInfo != null&&taskInfo.result!=Jing.RESULT_OK){//失败
                            String describe=describeErr(taskInfo.result);
                            if (describe!=null)errMsg+=describe;
                            errorDialog(context,R.string.title_err_create_project,errMsg).show();
                        }
                        else
                        if (taskInfo!=null& NewFileDialogBuilder.this.builderInterface!=null){//成功
                            //送出第一个java文件和pro文件
                            builderInterface.onFileCreated(taskInfo.filesToOpen.get(0));
                            builderInterface.onFileCreated(taskInfo.filesToOpen.get(1));
                        }

                    }
                });
        return dialogBuilder.create();

    }


    public AlertDialog errorDialog(Context context,int stringId,String msg){
        return errorDialog(context,context.getString(stringId),msg);
    }
    public AlertDialog errorDialog(Context context,String title,String msg){
        AlertDialog.Builder builder=new AlertDialog.Builder(context);
        builder.setTitle(title);
        builder.setMessage(msg);
        return  builder.create();
    }

    public AlertDialog buildFile(final Context context, final int type, final File dir, final File proFile) {

        final FileConstructor fileConstructor = new FileConstructor();
        final File srcDir = proFile == null ? null : fileConstructor.getSrcDir(proFile);
        final AlertDialog.Builder builder = new AlertDialog.Builder(context);
        final EditText edit = new EditText(context);
        edit.setText(Jing.FILE_TYPES[type]);
        edit.setSelection(0);

        builder.setTitle("新建文件")
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        String fileName=edit.getText().toString();
                        String msg = "";

                        String check= StringCheck.checkProjectFileName(fileName);
                        if (check!=null){
                            errorDialog(context,R.string.title_err_in_filename,check).show();
                            return;
                        }

                        File file = new File(dir.getAbsolutePath() + '/' + fileName);
                        int result = 0;
                        try {
                            result = fileConstructor.construct(type, file, srcDir);
                        } catch (IOException e) {
                            e.printStackTrace();
                            msg = "严重的错误，无法创建文件：" + msg + e.toString() + ";\n";
                        }
                        if (result!=1) {
                            String errDescribe = describeErr(result);
                            if (errDescribe != null) msg += errDescribe;
                        }else if (NewFileDialogBuilder.this.builderInterface!=null){
                            NewFileDialogBuilder.this.builderInterface.onFileCreated(file);
                        }

                        if (msg.length() > 0) {
                            AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
                            AlertDialog errorDialog = builder1.setTitle("出错了").setMessage(msg).create();
                            errorDialog.show();
                        }
                    }
                }).setNegativeButton(android.R.string.cancel, null);

        return builder.create();
    }

    private String describeErr(int type) {
        switch (type) {
            case Jing.UNKOWN_ERROR:
                return "创建文件时发生了错误 ";
            case Jing.FILE_EXISTED:
                return "文件已经存在了";
            case Jing.PARENT_DIR_NOT_EXIST:
                return "母文件夹不存在，无法创建其后的文件";
            case Jing.ILLEGAL_CHAR:
                return "文件名或路径中含有不合适的字符";
            default:
                return null;
        }
    }

    public interface FileBuilderI {
        void onFileCreated(File f);
    }

}
